<?php
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
class ShopCategory extends AppModel {
	public function findAllData(){
		return $this->find("all");
	}
	/**
	 * @author QuocTran
	 */
	public function findShopCategoryByShopId($shopId, $userId = -1){
		if ($userId == -1){
		   $data = $this->query("SELECT a.id as shopCatId, a.category_id as catId ,c.short_link, c.category_name,b.id as rootId, b.category_name as rootName  from shop_categories a, root_categories b, categories as c where
		          a.shop_id =".$shopId." and a.category_id = c.category_id and
		          b.id = a.root_category_id");
		  }else{
		   $data = $this->query("SELECT a.id as shopCatId, a.category_id as catId ,c.short_link, c.category_name,b.id as rootId, b.category_name as rootName  from shop_categories a, root_categories b, categories as c where
		          a.shop_id =".$shopId." and a.created_by = ".$userId." and a.category_id = c.category_id and
		          b.id = a.root_category_id");
		  }
		
		$arr =  array();
		foreach ($data as $item) {
			if(!isset($arr[$item['b']['rootId']])){
				$arr[$item['b']['rootId']] =array('rootId' => $item['b']['rootId'], 
												  'rootName'=>$item['b']['rootName'],  
												  'shopCat'=>array());
			}
			
			$temp['shopCatId'] = $item['a']['shopCatId'];
			$temp['catId'] = $item['a']['catId'];
			$temp['category_name'] = $item['c']['category_name'];
			$temp['short_link'] = $item['c']['short_link'];
			
			array_push($arr[$item['b']['rootId']]['shopCat'],$temp);
		} 
		// echo "<pre>";
		// print_r($arr);
		// exit;
		return $arr;
	}

	/*
	 * Get shop categories
	 * @author ThanhTran
	 *
	 */
	public function findByShopId($id = null){
		return $this->find('all',array(
			'recursive' => 1,
			'conditions' => array('ShopCategory.shop_id'=>$id),
			'fields' => array('category_id'),
			'contain' => array('Category')
			));
	}

	public $hasMany = array(
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'category_id',
            'fields' => array('category_name','short_link')
        ));
	
	/**
	 * @author quocTran
	 */
	 public function updateShopCategory($shopId, $arrShopCat){
	 	$dataSource = $this->getDataSource();
		try {
			
			$dataSource->begin();
		    $deleted = $this->deleteAll(array('ShopCategory.shop_id' => $shopId), false);
			$save = $this->saveMany($arrShopCat);
			
			$dataSource->commit();
			return true;
		} catch (Exception $e) {
		   $dataSource->rollback();
		}
		return false;
	}
	 
}
